package com.yyk.yykywd.ui.mine;

import android.os.Bundle;
import android.os.CountDownTimer;
import com.google.android.material.textfield.TextInputEditText;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yykywd.BusinessPeopleInfoKt;
import com.yyk.yykywd.R;
import com.yyk.yykywd.base.BaseActivity;
import com.yyk.yykywd.bean.AlidayuSendsmsInfo;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.CenterCheckyzmInfo;
import com.yyk.yykywd.util.BtnToEditListenerUtils;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.OnClickFlagUtil;
import com.yyk.yykywd.util.ToastUtil;


import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 更改手机号
 */
public class ChangePhotonumberActivity extends BaseActivity {

    @BindView(R.id.et_phone)
    TextInputEditText etPhone;
    @BindView(R.id.et_sms)
    TextInputEditText etSms;
    @BindView(R.id.tv_sendsms)
    TextView tvSendsms;
    @BindView(R.id.bt_next)
    Button btNext;
    private TimeCount timeCount;

    @Override
    public int getLayoutId() {
        return R.layout.activity_change_photonumber;
    }

    @Override
    public void initView() {
        initToolbar();
        initEdittext();
    }

    /**
     * 监听手机号和密码是否不为空：button按钮颜色变亮
     */
    private void initEdittext() {
        BtnToEditListenerUtils.getInstance().setBtn(btNext).setBackgroud(R.drawable.blue_51_6dip_bg_bt, R.drawable.blue_8b_6dip_bg_bt)
                .addEditView(etPhone)
                .addEditView(etSms)
                .build();
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("更改手机号");
    }

    @Override
    public void initData() {
        etPhone.setText(BusinessPeopleInfoKt.getPhone());
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @OnClick({R.id.tv_sendsms, R.id.bt_next})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_sendsms:
                if (etPhone.length() == 11) {
                    sendSms();
                } else {
//                    ToastUtil.showShort(mActivity, "手机号码不正确");
                    return;
                }

                break;
            case R.id.bt_next:
                verifyNext();
                break;
        }
    }

    /**
     * 验证手机号进入下一步
     */
    private void verifyNext() {
        final String phone = etPhone.getText().toString().trim();
        String sms = etSms.getText().toString().trim();
        if (phone.length() != 11) {
            ToastUtil.showShort(mActivity, "手机号格式不正确");
            return;
        }
        if (sms.length() != 4) {
            ToastUtil.showShort(mActivity, "验证码格式不正确");
            return;
        }
        Map<String, String> map = new TreeMap<>();
        map.put("uid", BusinessPeopleInfoKt.getUid());
        map.put("code", sms + "");
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postCenterCheckyzm(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Observer<CenterCheckyzmInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CenterCheckyzmInfo info) {
                        Logger.e("验证旧的手机号" + info.toString());
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(mActivity, info.getMsg());
                            Bundle bundle = new Bundle();
                            bundle.putString("phone", phone);
                            startAct(NewPhototnumberActivity.class, true, bundle);
                        } else if (info.getCode() == 0) {
                            ToastUtil.showShort(mActivity, "请检查手机号是否正确");
                        } else {
                            ToastUtil.showShort(mActivity, "验证码不正确");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 发送验证码
     */
    private void sendSms() {
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone) && phone.length() != 11) {
//            ToastUtil.showShort(RegisterActivity.this, "请输入手机号码");
            return;
        }
        Map<String, String> map = new TreeMap<>();
        map.put("telphone", phone + "");
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postAlidayuSendmss(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Observer<AlidayuSendsmsInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(AlidayuSendsmsInfo alidayuSendsmsInfo) {
                        Logger.e("发送验证码" + alidayuSendsmsInfo.toString());
                        if (alidayuSendsmsInfo.getCode() == 1) {
//                            ToastUtil.showShort(RegisterActivity.this, "获取验证码");
                            timeCount = new TimeCount(60000, 1000);
                            timeCount.start();
                        } else {
                            ToastUtil.showShort(mActivity, "请输入手机号");
                            return;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 设置 60秒时间 倒计时
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendsms.setClickable(false);
            tvSendsms.setText(millisUntilFinished / 1000 + "s后重发");
        }

        @Override
        public void onFinish() {
            tvSendsms.setText("获取验证码");
            tvSendsms.setClickable(true);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null) {
            timeCount.cancel();
        }
    }
    /*---------------------------------------------------------------------------------------------------------------------------*/

    /**
     * TODO  以后再研究
     * 为了实现 当 手机号和验证码有值的时候  button 变亮，否 变黑
     */

    private boolean Flag = false; //是否处于账号和密码不为空

    public void ZZZZ() {
        btNext.setBackgroundResource(Flag ? R.drawable.blue_51_6dip_bg_bt : R.drawable.blue_8b_6dip_bg_bt);
    }


}
